package com.dream.oproject.web.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

public class ApplicationUtil {
	private static final ObjectMapper objectMapper = new ObjectMapper();
	/**
	 * json转化为bean
	 * 
	 * @param <T>
	 * @param body
	 * @param valueType
	 * @return
	 */
	public static <T> T convertJsonToBean(String body, Class<T> valueType) {
		try {
			return objectMapper.readValue(body, valueType);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static <T> List<T> convertJsonToListBean(String body, Class<T> beanClass) {
		List<T> list = null;
		try {
			list   = objectMapper.readValue(body, TypeFactory.collectionType(ArrayList.class, beanClass));
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	
	public static String convertBeanToJson(Object valueType) {
		try {
			return objectMapper.writeValueAsString(valueType);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
	}
}